package com.tiyende.credit.loop.utils.helper

import com.tiyende.credit.loop.utils.TiyendeDateUtil
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/18 16:56
 * @Annotation：订单
 */
object TiyendeOrderHelper {

    private var orderData: JSONObject? = null

    /**
     * 保存订单数据
     */
    fun saveTiyendeOrderData(data: JSONObject){
        orderData = data
    }

    /**
     * 获取订单数据
     */
    private fun queryTiyendeOrderData(): JSONObject?{
        if (orderData != null){
            return orderData
        }
       return JSONObject()
    }

    /**
     * 获取订单列表
     */
    fun queryTiyendeOrderList(): ArrayList<JSONObject>{
        val orderList = arrayListOf<JSONObject>()
        val orderData = queryTiyendeOrderData() ?: return orderList

        if (orderData.has("loanList")){
            val loanList = orderData.optJSONArray("loanList")
            val timeStamp = orderData.optLong("timeStamp")
            if (loanList != null) {
                for (i in 0..< loanList.length()){
                    val orderItem = loanList.optJSONObject(i)
                    orderItem.put("timeStamp",timeStamp)
                    //状态异常订单,不显示
                    if (orderItem.optString("orderStatus") == "NO"){
                        continue
                    }
                    orderList.add(orderItem)
                }
            }
        }
        return orderList
    }

    /**
     * 获取待还款订单列表
     */
    fun queryTiyendeOrderRepayList(): ArrayList<JSONObject>{
        val repayList = arrayListOf<JSONObject>()
        val orderList = queryTiyendeOrderList()
        if (orderList.size == 0){
            return repayList
        }
        orderList.forEach {
            val orderStatus = it.optString("orderStatus")
            if (orderStatus.contains("WAIT_REPAY")){
                //还款时间转为时间戳
                val repayTimeStamp = TiyendeDateUtil.convertDateToTimestamp("MM/dd/yyyy",it.optString("repayTime"))
                //保存剩余还款天数
                it.put("remainRepayDay", TiyendeDateUtil.getDaysFromTimestamps(it.optLong("timeStamp"),repayTimeStamp))
                repayList.add(it)
            }
        }
        return repayList
    }

    /**
     * 获取除待还款订单外的订单列表
     */
    fun queryTiyendeOrderOtherList(): ArrayList<JSONObject>{
        val otherList = arrayListOf<JSONObject>()
        val orderList = queryTiyendeOrderList()
        if (orderList.size == 0){
            return otherList
        }
        orderList.forEach {
            val orderStatus = it.optString("orderStatus")
            if (!orderStatus.contains("WAIT_REPAY")){
                otherList.add(it)
            }
        }
        return otherList
    }
}